package com.example.industry.dao.impl;

import com.example.industry.MyMailSender;
import com.example.industry.MySqlConnector;
import com.example.industry.dao.InviteDao;
import com.example.industry.entity.Invite;
import org.springframework.stereotype.Repository;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

@Repository
public class InviteDaoImpl implements InviteDao {
    @Override
    public Boolean addInvite(Invite invite) {
        MyMailSender myMailSender = new MyMailSender();
        if (invite == null || invite.getMailFrom() == null ||
        invite.getMailTo() == null || invite.getDescription() == null) return Boolean.FALSE;
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            String sql = "insert into invite ( invite_mail_from,invite_mail_to,invite_description ) values( " + invite.getMailFrom() + "," +
                    invite.getMailTo() + "," + invite.getDescription() + ")";
            try (Statement stmt = conn.createStatement())
            {
                int result = stmt.executeUpdate(sql);
                if (result > 0) {
                    myMailSender.sendTextMailMessage(invite.getMailTo(),"Invite You To Join Our Team.",invite.getDescription());
                    return Boolean.TRUE;
                }
            }
            connector.closeConnection();
            return Boolean.FALSE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }

    @Override
    public Invite findInviteById(Integer id) {
        Invite invite = new Invite();
        MySqlConnector connector = new MySqlConnector();
        try
        {
            connector.connectDatabase();
            Connection conn = connector.getConnection();
            String sql = "select * from invite where invite_id = " + id;
            try (Statement stmt = conn.createStatement())
            {
                ResultSet resultSet = stmt.executeQuery(sql);
                if (resultSet.next())
                {
                    invite.setMailFrom(resultSet.getString("invite_mail_from"));
                    invite.setMailTo(resultSet.getString("invite_mail_to"));
                    invite.setDescription(resultSet.getString("invite_description"));
                }
                else
                {
                    invite = null;
                }
            }
            connector.closeConnection();
            return invite;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
}
